package garage

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/garage"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
    garageReq "github.com/flipped-aurora/gin-vue-admin/server/model/garage/request"
)

type GarageService struct {
}

// CreateGarage 创建garage表记录
// Author [piexlmax](https://github.com/piexlmax)
func (garagesService *GarageService) CreateGarage(garages *garage.Garage) (err error) {
	err = global.GVA_DB.Create(garages).Error
	return err
}

// DeleteGarage 删除garage表记录
// Author [piexlmax](https://github.com/piexlmax)
func (garagesService *GarageService)DeleteGarage(garages garage.Garage) (err error) {
	err = global.GVA_DB.Delete(&garages).Error
	return err
}

// DeleteGarageByIds 批量删除garage表记录
// Author [piexlmax](https://github.com/piexlmax)
func (garagesService *GarageService)DeleteGarageByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]garage.Garage{},"id in ?",ids.Ids).Error
	return err
}

// UpdateGarage 更新garage表记录
// Author [piexlmax](https://github.com/piexlmax)
func (garagesService *GarageService)UpdateGarage(garages garage.Garage) (err error) {
	err = global.GVA_DB.Save(&garages).Error
	return err
}

// GetGarage 根据id获取garage表记录
// Author [piexlmax](https://github.com/piexlmax)
func (garagesService *GarageService)GetGarage(id uint) (garages garage.Garage, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&garages).Error
	return
}

// GetGarageInfoList 分页获取garage表记录
// Author [piexlmax](https://github.com/piexlmax)
func (garagesService *GarageService)GetGarageInfoList(info garageReq.GarageSearch) (list []garage.Garage, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&garage.Garage{})
    var garagess []garage.Garage
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
     db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
    }
	err = db.Count(&total).Error
	if err!=nil {
    	return
    }

	if limit != 0 {
       db = db.Limit(limit).Offset(offset)
    }
	
	err = db.Find(&garagess).Error
	return  garagess, total, err
}
